﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Threading;

namespace DatabaseEntegreItri.Utils
{
    public class FileWatcher
    {
        String file;
        EventHandler handler;
        Dispatcher disp;
        FileSystemWatcher watch;
        public FileWatcher(String fileName,EventHandler handler,Dispatcher disp)
        {
            this.disp = disp;
            this.handler=handler;
            file = fileName;
            watch = new FileSystemWatcher();
            FileInfo inf = new FileInfo(fileName);
            watch.Path = inf.Directory.ToString();
            watch.Filter = inf.Name;

            watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;           
            
            watch.Deleted += new FileSystemEventHandler(OnDeleted);
            watch.Renamed += new RenamedEventHandler(OnRenamed);            

            watch.EnableRaisingEvents = true;            
        }
        public void stopWatcher() {

            if (watch != null) {
                watch.Dispose();
            }
        }

        private  void OnDeleted(object source, FileSystemEventArgs e)
        {
            file = "";
            disp.Invoke(handler, file, null);
            //handler.Invoke(file,null);
            // Specify what is done when a file is changed, created, or deleted.
            //if (e.FullPath == @"D:\tmp\p.txt")
              //  Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);

        }

        private void OnRenamed(object source, RenamedEventArgs e)
        {
            file = e.FullPath;
            disp.Invoke(handler, file, null);
            watch.Filter = e.Name;           
        }
    }
}
